const app = getApp();
const api = require('../../utils/api');
const md5 = require('../../utils/md5');

var animation = {};

let startDate = ''; //设置开始日期（今天）
let startTime = ''; //设置开始时间（半小时后）

let now = new Date(); //现在时间
let year = now.getFullYear();
let month = now.getMonth() + 1;
let day = now.getDate();

let time = now.getTime() + 1000*60*30; //延后半个小时
let newTime = new Date(time);

startDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day); //格式化日期
startTime = newTime.getHours() + ':' + newTime.getMinutes(); //格式化时间

Page({
    data: {
        isStoreManager: false, //是否店长

        type: 1, //0 默认店铺 1 可以切换店铺
        shopId: '', //提货店铺id
        storeInfo: '', //提货店铺信息
        productList: [], //商品列表

        totalNumber: 0, //数量合计
        totalPrice: 0, //价格合计
        totalCoupon: 0, //购物券合计

        pointAccount: 0, //积分余额
        couponAccount: 0, //购物券余额
        couponAccountShow: 0, //购物券余额（显示用）
        memberAccount: 0, //店铺会员账户余额
        canUseAccountBalance: false, //是可以使用店铺账户余额
        
        isUseCoupon: false, //是否选择购物券支付
        isUseAccountBalance: false, //是否选择账户余额支付
        isUsePacking: false, //是否需要打包
        isBooking: false, //是否预约上门时间
        isPurchaseAgent: false, //是否代购
        
        bookDate: '', //预约日期
        bookTime: '', //预约时间
        today: startDate,
        startDate: startDate,
        startTime: startTime,

        buyerPhone: '', //购买人电话（搜索用）
        buyerId: '', //代购模式下，购买人id
        buyerPhone: '',
        buyerNickName: '',
        buyerCouponAccount: '', //购买人券余额

        buyCouponAnimation: {}, //购物券列表弹窗的动画效果
        isShowLayer: false, //弹窗遮罩层
        couponList: [], //购物券商品列表
        couponItemSelected: '', //选择要购买的购物券商品

        showPassword: false, //支付密码弹窗
        couponOrderId: '',
        payPassword: '',
        isSetPayPassword: true, //是否已经设置支付密码

        inviteCode: '', //邀请人的邀请码
    },
    onLoad(options) {
        console.log(options)
        this.setData({
            shopId: options.shopId ? parseInt(options.shopId) : 0,
            type: parseInt(options.dir) ? parseInt(options.dir) : 0,
            inviteCode: options.inviteCode ? options.inviteCode : '',
        });
        this.initData();
    },
    onShow() {
        animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease-out',
        });
        this.setData({
            isSetPayPassword : app.globalData.userInfo.isSetPayPassword == 1 ? true : false,
        });

        //刷新提货店铺信息
        if(app.globalData.isRefreshPickipStore) {
            this.setData({
                shopId: wx.getStorageSync('pickup'),
            });
            this.getStoreInfo();
            
            app.globalData.isRefreshPickipStore = false; //还原状态
            wx.removeStorageSync('pickup'); //清除缓存
        }
    },
    initData() { //初始化数据
        //商品列表
        let list = app.globalData.shopcartCacheList;
        this.setData({
            productList: list
        });
        this.dealSummary(); //计算总数

        //商品中是否有可以账户余额购买的商品
        for(let i in this.data.productList) {
            if(this.data.productList[i].rechargePrice) {
                this.setData({
                    canUseAccountBalance: true,
                });
                break;
            }
        }
        if(this.data.canUseAccountBalance && this.data.type === 0) {
            this.getMemberAccount(); //有可以账户余额购买的商品，获取账户余额信息
        }
        this.getCouponAccount(); //获取券账户信息
        this.getPointAccount(); //获取账户积分信息
        
        if(this.data.shopId) {
            this.getStoreInfo(); //获取店铺信息
        }
        if(this.data.type == 1) {
            this.getFrequentlyUsedStoreList(); //获取常用提货店铺
        }
    },
    getStoreInfo() { //获取提货店铺信息
        api.post('/shop/detail?shopId=' + this.data.shopId)
            .then(res => {
                this.setData({
                    storeInfo: res
                })
            })
    },
    getFrequentlyUsedStoreList() { //获取常用店铺列表
        api.post(`/user/pickup/address/list`)
            .then(res => {
                res.forEach(item => {
                    if(item.isDefault) {
                        this.setData({
                            storeInfo: item,
                            shopId: item.shopId,
                        });
                    }
                });
            })
    },
    gotoChangeShop() { //去切换提货店铺
        if(this.data.type == 0) {
            return;
        }
        if(this.data.isPurchaseAgent) {
            wx.showToast({
                title: '代购的提货店铺，只能是本人管理的店铺！',
                icon: 'none'
            });
            return;
        }
        wx.navigateTo({
            url: '/pages/storeChange/storeChange?dir=1&shopId=' + this.data.shopId,
        });
    },

    getCouponAccount() { //获取个人信息，和购物券余额
        api.post('/user/info')
            .then(res => {
                //保存用户信息，防止有些人操作过快没有保存信息
                wx.setStorageSync('userinfo', res);
                app.globalData.userInfo = res;

                this.setData({
                    couponAccount: res.balance,
                    couponAccountShow: res.balance,
                    isStoreManager: res.bindShopId && (this.data.shopId == res.bindShopId || this.data.shopId == 0) ? true : false, //是否可以代购（非本人店铺不可代购）
                });
            })
    },
    getMemberAccount() { //获取店铺会员账户余额
        api.post(`/user/account/info?shopId=${this.data.shopId}`)
            .then(res => {
                this.setData({
                    memberAccount: res.balance,
                })
            })
    },
    getPointAccount() { //获取积分账户余额
        api.post(`/user/member/account`)
            .then(res => {
                this.setData({
                    pointAccount: res.balance
                });
            })
    },

    //订单选项处理
    dealSummary() { //计算商品总数和价格、券数量
        let sum = 0; //总件数
        let price = 0; //总价格
        let coupon = 0; //购物券数量
        
        let list = this.data.productList;
        list.forEach(item => {
            sum = sum + item.quantity; //数量
            if(this.data.isUseCoupon) { //价格
                //使用购物券
                if(item.productType == 1) {
                    price = price + parseFloat(item.price * item.quantity);
                } else {
                    price = price + parseFloat(item.memberPrice * item.quantity);
                }
            } else if(this.data.isUseAccountBalance) {
                //使用账户余额支付
                price = price + (item.rechargePrice ? parseFloat(item.rechargePrice * item.quantity) : parseFloat(item.price * item.quantity));
            } else {
                price = price + parseFloat(item.price * item.quantity);
            }
            //购物券数量
            coupon = coupon + parseFloat(item.couponAmount * item.quantity);
        });
        //加打包费
        if(this.data.isUsePacking) {
            price = price + this.data.storeInfo.balingCharges;
        }
        //如果购物券数量有小数点，处理一下小数点
        let digitNum = coupon.toString().split('.').length > 1 ? coupon.toString().split('.')[1] : [];
        if(digitNum.length > 2) {
            coupon = coupon.toFixed(2);
        }

        this.setData({
            totalNumber: sum, //件数总计
            totalPrice: price.toFixed(2), //应付金额总计
            totalCoupon: coupon, //购物券总计
        });
    },
    choosePayByCoupon() { //是否用券
        let isUse = this.data.isUseCoupon;
        this.setData({
            isUseCoupon: !isUse,
            isUseAccountBalance: false,
        });
        this.dealSummary();
    },
    choosePayByAccount() { //是否账户余额支付
        let isUse = this.data.isUseAccountBalance;
        this.setData({
            isUseAccountBalance: !isUse,
            isUseCoupon: false,
        });
        this.dealSummary();
    },
    choosePackage() { //是否打包
        let isUse = this.data.isUsePacking;
        if(isUse) {
            this.setData({
                isUsePacking: !isUse
            });
            this.dealSummary();
        } else {
            if(this.data.shopId == '') {
                wx.showToast({
                    title: '请先选择提货店铺',
                    icon: 'none'
                });
                return;
            }
            this.setData({
                isUsePacking: !isUse
            });
            this.dealSummary();
        }
    },
    chooseBooking() { //是否预约上门时间
        let isUse = this.data.isBooking;
        this.setData({
            isBooking: !isUse
        });
    },
    bindDateChoose(e) { //选择预约日期
        this.setData({
            bookDate: e.detail.value,
            bookTime: e.detail.value == this.data.today && this.data.bookTime === '' ? '' : e.detail.value != this.data.today && this.data.bookTime ? this.data.bookTime : this.data.startTime,
            startTime: e.detail.value == this.data.today ? startTime : ''
        });
    },
    bindTimeChoose(e) { //选择预约时间
        this.setData({
            bookTime: e.detail.value
        });
    },
    choosePurchaseAgent() { //是否代购
        let isAgent = this.data.isPurchaseAgent;
        this.setData({
            isPurchaseAgent: !isAgent,
            isUseCoupon: false,
        });
        if(this.data.type) {
            this.setData({
                shopId: app.globalData.userInfo.bindShopId,
            });
            this.getStoreInfo();
        }
        this.dealSummary();
    },

    searchPurchaseBuyer() { //查询购买人
        if(!this.data.buyerPhone) {
            wx.showToast({
                title: '请填写购买人电话！',
                icon: 'none'
            });
            return;
        }
        if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.data.buyerPhone))) {
            wx.showToast({
                title: '请检查手机号是否正确！',
                icon: 'none'
            });
            return;
        }
        api.post(`/user/info/simple?userPhone=${this.data.buyerPhone}`)
            .then(res => {
                this.setData({
                    buyerId: res.id,
                    buyerPhone: res.phone,
                    buyerNickName: res.nickName,
                    buyerCouponAccount: res.balance
                });
            })
            .catch(() => {
                this.setData({
                    buyerId: '',
                    buyerPhone: '',
                    buyerNickName: '',
                    buyerCouponAccount: '',
                    isUseCoupon: false,
                });
                this.dealSummary();
            })
    },

    //购买购物券
    openBuyCouponBox() { //打开购券弹窗
        animation.bottom('0').step();
        this.setData({
            buyCouponAnimation: animation.export(),
            isShowLayer: true
        });

        let params = {
            saleChannel: 0,
            couponType: 0,
            pageNum: 1,
            pageSize: 100
        }
        api.post('/coupon/product/list', params)
            .then(res => {
                this.setData({
                    couponList: res
                })
            })
    },
    closeBuyCouponBox() { //关闭购券弹窗
        animation.bottom('-100%').step();
        this.setData({
            buyCouponAnimation: animation.export(),
            couponItemSelected: '',
            isShowLayer: false
        });
    },
    chooseCoupon(e) { //选择购物券
        let item = e.currentTarget.dataset.item;
        this.setData({
            couponItemSelected: item
        });
    },
    buyCouponByPoint() { //积分直接购券
        if(this.data.couponItemSelected.id === undefined) {
            wx.showToast({
                title: '请选择要购买的券',
                icon: 'none'
            });
            return;
        }
        if(this.data.couponItemSelected.couponCredits > this.data.pointAccount) {
            wx.showToast({
                title: '您的积分余额不足',
                icon: 'none'
            });
            return;
        }
        if(!this.data.isSetPayPassword) {
            //如果没有设置支付密码，提醒去设置
            wx.showModal({
                title: '温馨提示',
                content: `您还未设置支付密码！`,
                confirmText: '去设置',
                cancelText: '晚点设置',
                success: res => {
                    if(res.confirm) {
                        wx.navigateTo({
                            url: '/pages/setPayPassword/setPayPassword',
                        })
                    } else {
                        this.closeBuyCouponBox();
                    }
                }
            });
            return;
        }
        let params = {
            productId: this.data.couponItemSelected.id,
            orderQuantity: 1,
            couponPrice: this.data.couponItemSelected.couponPrice,
            couponCredits: this.data.couponItemSelected.couponCredits,
            orderAmount: this.data.couponItemSelected.couponPrice,
            orderAmountCredit: this.data.couponItemSelected.couponCredits,
            payAmount: this.data.couponItemSelected.couponPrice, //实付金额
            payAmountCredits: this.data.couponItemSelected.couponCredits, //实付积分
        }
        api.post('/coupon/order/add', params)
            .then(res => {
                this.setData({
                    couponOrderId: res,
                    showPassword: true,
                });
            })
    },
    addCouponToShopcart() { //加入购物车
        if(this.data.couponItemSelected.id === undefined) {
            wx.showToast({
                title: '请选择要购买的券',
                icon: 'none'
            });
            return;
        }
        let list = this.data.productList;
        //查找是否已经添加过券
        let index = list.findIndex(item => {
            return item.productType == 1 && item.productCouponId == this.data.couponItemSelected.id;
        });
        if(index > -1) {
            list[index].quantity++;
        } else {
            list.push({
                productCouponId: this.data.couponItemSelected.id,
                productType: 1,
                productSkuSaleImage: this.data.couponItemSelected.thumbImage,
                productName: this.data.couponItemSelected.productName,
                productSkuSaleName: this.data.couponItemSelected.couponDenomination,
                price: this.data.couponItemSelected.couponPrice.toFixed(2),
                couponAmount: 0,
                quantity: 1,
                couponDenomination: this.data.couponItemSelected.couponDenomination,
            });
        }
        
        let couponAccount = this.data.couponAccount; //更新购物券余额
        this.setData({
            productList: list,
            couponAccount: couponAccount + this.data.couponItemSelected.couponDenomination
        });

        this.dealSummary();
        this.closeBuyCouponBox();
    },
    deleteCoupon(e) { //删除购物券
        let index = e.currentTarget.dataset.index;
        //更新购物券余额
        let couponAccount = this.data.couponAccount;
        let accountChange = this.data.productList[index].productSkuSaleName;
        this.setData({
            couponAccount: couponAccount - accountChange,
        })
        //删除券
        let list = this.data.productList;
        list.splice(index, 1);
        this.setData({
            productList: list,
        });
        this.dealSummary();
    },
    //购买购物券：输入密码、提交支付
    bindinput(e) { //输入框监听
        let item = e.currentTarget.dataset.item;
        let val = e.detail.value;
        this.setData({
            [item]: val
        });
    },
    submitPassword() { //提交支付密码
        if(!this.data.payPassword) {
            wx.showToast({
                title: `请输入支付密码`,
                icon: 'none'
            });
            return;
        }
        
        let password = this.data.payPassword;
        api.post('/payment/credits/pay', {
            orderId: this.data.couponOrderId,
            abc: md5.md5(password)
        })
            .then(() => {
                wx.showToast({
                    title: '购券成功',
                    icon: 'success'
                });

                this.getCouponAccount(); //刷新余额
                this. closePassword();
                this.closeBuyCouponBox();
            })
    },
    closePassword() { //关闭支付密码弹窗
        this.setData({
            payPassword: '',
            showPassword: false,
        });
    },
    gotoSetPassword() { //去设置支付密码
        wx.navigateTo({
            url: '/pages/setPayPassword/setPayPassword',
        });
    },

    submitOrder() { //提交订单
        if(!this.data.shopId) {
            wx.showToast({
                title: '请选择提货店铺！',
                icon: 'none'
            });
            return;
        }
        if(this.data.isUseCoupon && !this.data.isPurchaseAgent && this.data.totalCoupon > this.data.couponAccount) {
            wx.showToast({
                title: '您的购物券余额不足！',
                icon: 'none'
            });
            return;
        }
        if(this.data.isUseCoupon && this.data.isPurchaseAgent && this.data.totalCoupon > this.data.buyerCouponAccount) {
            wx.showToast({
                title: '购物券账户余额不足！',
                icon: 'none'
            });
            return;
        }
        if(this.data.isBooking && !this.data.bookDate) {
            wx.showToast({
                title: '请选择预约日期！',
                icon: 'none'
            });
            return;
        }
        if(this.data.isBooking && !this.data.bookTime) {
            wx.showToast({
                title: '请选择预约时间！',
                icon: 'none'
            });
            return;
        }

        let params = {
            shopId: this.data.shopId, //店铺ID，系统不支持跨店铺下单
            shopNo: this.data.storeInfo.shopNo, //店铺编号
            orderType: this.data.isPurchaseAgent ? 1 : 2, //订单类型: 1零售订单、2商城自提、3商城物流、5线下收款
            balingCharges: this.data.isUsePacking ? this.data.storeInfo.balingCharges : 0, //打包费，不选择打包费则传0
            isMemberPay: this.data.isUseCoupon ? 1 : 0, //是否用会员结算 0.否 1.是
            isAccountPay: this.data.isUseAccountBalance ? 1 : 0, //是否用充值会员账户结算 0.否 1.是
            orderTotalAmount: parseFloat(this.data.totalPrice), //订单总金额
            payableAmount: parseFloat(this.data.totalPrice), //应付金额
            couponAmount: this.data.totalCoupon, //应付券金额，订单中所有商品的券金额之和
            couponSyncBuy: 0, //同步购券的总面额，没有则填0
            planPickupTime: this.data.isBooking ? this.data.bookDate + ' ' + this.data.bookTime + ':00' : '',
            invitationCode: this.data.inviteCode, //邀请人
            orderDetailVos: [], //商品列表
        }
        let buyCoupon = 0; //购券金额
        this.data.productList.forEach(item => {
            params.orderDetailVos.push({
                productType: item.productType ? 1 : 0, //商品类型：0普通商品 1优惠券商品
                cartId: item.id, //购物车明细ID
                saleProductId: item.productType ? '' : item.productSkuSaleId, //销售商品ID
                productCouponId: item.productType ? item.productCouponId : '',
                quantity: item.quantity,
            })
            if(item.productType == 1) {
                buyCoupon = buyCoupon + (item.couponDenomination * item.quantity);
            }
        });
        params.couponSyncBuy = buyCoupon;

        if(this.data.isPurchaseAgent && this.data.buyerId) { //如果是代购模式
            params.customerUserId = this.data.buyerId;
            params.customerUserPhone = this.data.buyerPhone;
            params.customerUserNickName = this.data.buyerNickName;
        }

        api.post('/order/submit', params)
            .then(res => {
                wx.showToast({
                    title: '下单成功',
                    icon: 'success'
                });

                app.globalData.isRefreshShopcart = true;
                setTimeout(() => {
                    if(this.data.isPurchaseAgent) {
                        wx.redirectTo({
                            url: `/pages/orderPay/orderPay?id=${res}&dir=1`,
                        });
                    } else {
                        wx.redirectTo({
                            url: `/pages/orderPay/orderPay?id=${res}`,
                        });
                    }
                }, 1000);
            })
    },
})